#!/usr/bin/envpython
# -*-coding:UTF-8-*-
'''
@File    :   globa_depends_fun.py
@Contact :   308711822@qq.com
@License :   (C) Copyright 2021-2225, Personal exclusive right.

@Modify Time      @Author    @Version    @Desciption
------------      -------    --------    -----------
2023/2/4 16:23   小钟同学      1.0         None
'''
from contextlib import asynccontextmanager
from typing import AsyncGenerator
from sqlalchemy.exc import SQLAlchemyError, OperationalError
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.ext.asyncio import AsyncSession

from afast_core.core_plugins.db.sqlalchemy import global_async_session
async def get_async_session_depends_globa() -> AsyncSession:
    """
    使用方法方式定义依赖项
    :param request: current request.
    :return: pyee_events producer from the core_app.
    """
    async with global_async_session() as session:
        # await async_session.commit()
        try:
            yield session
            # 使用自动提交在某些情况下 会突发的asyncio.exceptions.CancelledError异常
            # await async_session.commit()
        except SQLAlchemyError as ex:
            print(ex)
            await session.rollback()

        finally:
            # 1.4.0版本的话 需要收的执行关闭，才可以 不然会一直超时
            # 1.4.19的话 这个地方可以起到关闭的作用！
            await session.close()

@asynccontextmanager
async def get_async_session_context_globa() -> AsyncGenerator:
    '''
    下面的上下文的方式是基于全局变量的方式处理
    :return:
    '''
    async_session: AsyncSession = global_async_session()
    try:
        yield async_session
        # Exception during reset or similar
        # Traceback (most recent call last):
        # 使用自动提交在某些情况下 会突发的asyncio.exceptions.CancelledError异常
        # await async_session.commit()
    except OperationalError as ex:
        pass
        raise ex
    except SQLAlchemyError as ex:
        await async_session.rollback()
        raise ex
    finally:
        await async_session.close()